package com.wwc.controller;

import com.wwc.entities.CommonResult;
import com.wwc.entities.Payment;
import com.wwc.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/payment")
@Api(value = "PaymentController")
public class PaymentController{
	@Resource
	private PaymentService paymentService;
	@Resource
	private DiscoveryClient discoveryClient;
	
	@Value(value = "${server.port}")
	private String serverPort;
	
	
	@PostMapping(value = "/createPayment")
	@ApiOperation(value = "新增Payment数据")
	public CommonResult<Integer> createPayment(@RequestBody Payment payment){
		int result = paymentService.createPayment(payment);
		log.info("createPayment->result：{{}}", result);
		if(result > 0){
			return new CommonResult<>(200, "新增成功,serverPort：" + serverPort, result);
		}else{
			return new CommonResult<>(444, "新增失败");
		}
	}
	
	@GetMapping(value = "/getPaymentById/{id}")
	@ApiOperation(value = "根据id获取Payment数据")
	public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
		Payment payment = paymentService.getPaymentById(id);
		log.info("getPaymentById->payment:{{}}", payment);
		if(payment != null){
			return new CommonResult<>(200, "查询数据成功,serverPort：" + serverPort, payment);
		}else{
			return new CommonResult<>(444, "查询数据失败，id：" + id);
		}
	}
	
	@GetMapping(value = "/getDiscovery")
	@ApiOperation(value = "获取Discovery详情")
	public CommonResult<DiscoveryClient> getDiscovery(){
		discoveryClient.getServices()
				.forEach(s -> log.info("getDiscovery->service:{{}}", s));
		discoveryClient.getInstances("PAYMENT-SERVICE")
				.forEach(s -> log.info("getDiscovery->instance:{{}}", s.getServiceId() + " " + s.getPort() + " " + s.getUri()));
		return new CommonResult<>(200, "查询discovery成功", this.discoveryClient);
	}
	
	@GetMapping(value = "/getLoadBalanced")
	@ApiOperation(value = "获取LoadBalanced端口")
	public String getLoadBalanced(){
		return serverPort;
	}
	
	@GetMapping(value = "/getService")
	@ApiOperation(value = "获取服务名称")
	public CommonResult<List<String>> getService(){
		log.info("getService->this.discoveryClient:{{}}", this.discoveryClient);
		return new CommonResult<>(200, "查询Service成功", discoveryClient.getServices());
	}
	
	@GetMapping(value = "/feignTimeOut")
	@ApiOperation(value = "openfeign超时测试")
	public CommonResult<String> feignTimeOut(){
		log.info("feignTimeOut->serverPort:{{}}", serverPort);
		// 暂停几秒钟线程
		try{
			TimeUnit.SECONDS.sleep(3);
		}catch(InterruptedException e){
			log.error(e.toString());
		}
		return new CommonResult<>(200, "openfeign超时测试返回端口", serverPort);
	}
	
}
